package org.duiduo.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.duiduo.api.request.RoleLoginRequest;
import org.duiduo.api.response.RespBean;
import org.duiduo.pojo.Role;
import org.duiduo.service.IRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.security.Principal;

/**
 * 登录接口
 *
 * @author liangze
 */
@RestController
@Api(tags = {"登录相关"})
public class LoginController {

    @Autowired
    private IRoleService roleService;

    @ApiOperation(value = "登录之后返回token")
    @PostMapping("/login")
    public RespBean login(@RequestBody @Valid RoleLoginRequest roleLoginRequest, HttpServletRequest request) {
        return roleService.login(roleLoginRequest.getUsername(), roleLoginRequest.getPassword(), request);
    }

    @ApiOperation(value = "获取当前登录角色信息")
    @GetMapping("/role/info")
    public Role getAdminInfo(Principal principal) {
        if (null == principal) {
            return null;
        }
        String username = principal.getName();
        Role role = roleService.getRoleByUsername(username);
        role.setPassword(null);
        return role;
    }

}
